<?php


namespace app\api\controller;


use app\api\model\QwenModel;
use think\Db;
use think\Exception;

class Qwen extends ApiBase
{

    /**
     *
     * 添加AI聊天记录
     */
    public function qwenAdd(){

        $params = $this->request->post();
        $params['user_id'] = $this->id;
        if (!isset($params['case_id']) || empty($params['case_id'])){

            $this->fail('缺少病例id');
        }
        $res = QwenModel::qwenAdd($params);
        if ($res){

            $this->successful('操作成功',$res);
        }else{

            $this->fail('操作失败');
        }
    }

    /**
     *
     * 聊天添加
     */
    public function content(){

        try{

            Db::startTrans();
            $params = $this->request->post();
            $params['user_id'] = $this->id;
            if (!isset($params['pid']) || empty($params['pid'])){

                $this->fail('缺少上级id');
            }
            if (!isset($params['content']) || empty($params['content'])){

                $this->fail('缺少聊天内容');
            }
            $res1 = QwenModel::qwenAdd($params);

            #Qwen AI
            $data = [

                'model'=>'Qwen/Qwen1.5-7B-Chat-GGUF',
                'messages'=>[

                    [
                        'role'=>'user',
                        'content'=>$params['content'],
                    ]
                ]
            ];

            $headers = array("Content-Type: application/json");
            $result = postJsonCurl($data,'http://localhost:1234/v1/chat/completions',1,$headers);
            $result = json_decode($result,true);
            $params['content'] = $result['choices'][0]['message']['content'];
            $params['type'] = 1;
            $res2 =  QwenModel::qwenAdd($params);
            if ($res1 && $res2){

                Db::commit();
                $this->successful('发送成功',$params['content']);
            }else{

                Db::rollback();
                $this->fail('发送失败');
            }

        }catch (Exception $exception){
            Db::rollback();
            $this->fail($exception->getMessage());
        }

    }

    /**
     *
     * 聊天列表
     */
    public function contentList(){


        $params = $this->request->post();
        if (!isset($params['pid']) || empty($params['pid'])){

            $this->fail('缺少上级id');
        }
        $data = QwenModel::contentList($this->id,$params['pid']);
        $this->successful('查询成功',$data);
    }

}